
<template xmlns:el-col="http://www.w3.org/1999/html">


  <main role="main">


    <div class="album py-5 bg-light">

      <div class="container" >
        <el-row>
          <el-col :span="5">
            <el-button size="large" round type="primary" @click="foldSwitchStatus = !foldSwitchStatus">
              <span v-show="foldSwitchStatus">▲收起试题分类</span>
              <span v-show="!foldSwitchStatus">▼展开试题分类</span>
            </el-button>
          </el-col>


        </el-row>
        <br>

        <transition name="problemDetailDraw">
          <div class="fold-switch"  v-show="foldSwitchStatus" style="display: flex;flex-wrap:wrap;">
            <div v-for="(levelOne, index) in problemCategories" :key="index" style="cursor: pointer;">
              <div class="row col-lg-12">
                <span style="text-align: center;width: 120px" :class="activeItem.includes(levelOne.problemCategorySlug)?'active':'Classification'" @click="onCheck(levelOne.problemCategorySlug,levelOne.problemCategoryId)">{{levelOne.problemCategoryName}}</span>
              </div>
            </div>
          </div>
        </transition>

        <br>


        <div class="form-group">
          <label for="time-limit">已选试题分类</label>
          <input type="text" class="form-control" id="category-selected" placeholder="" v-model="selectedCategory" disabled >
        </div>


        <div class="form-group">

          <el-row>
            <el-col :span="8">
              <label>试题标签</label>
              <select class="form-control" id="problem-tag" v-model="tagId">
                <option v-for="(l,k) in tagList" :key="k" >{{l.name}}</option>
              </select>
            </el-col>

            <el-col :span="8" >
              <label>题型</label>
              <select class="form-control" id="problem-type" v-model="selectType"  >
                <option v-for="(l,k) in typeList" :key="k" >{{l.name}}</option>
              </select>
            </el-col>


<!--            <el-col :span="8" >-->
<!--              <label>所属公司</label>-->
<!--              <select class="form-control" id="problem-company" v-model="company"  >-->
<!--                <option v-for="(l,k) in companyList" :key="k" >{{l.name}}</option>-->
<!--              </select>-->
<!--            </el-col>-->

          </el-row>
        </div>

          <div class="addquestion">
            <div class="question_body">

              <el-form
                  :model="dynamicValidateForm"
                  ref="dynamicValidateForm"
                  label-width="100px"
                  class="demo-dynamic"
              >

                <el-form-item
                    label="题目内容"
                    :rules="[{ required: true, message: '请输入题目内容', trigger: 'blur' }]"
                >

                  <span v-if="keyword=='show'">1</span>
                  <el-input type="textarea" v-if="keyword!='show'" v-model="title" ></el-input>
                </el-form-item>

                <div class="domains_fileds">
                  <div class="domain_title">
                    <span>答题选项：</span>
                    <el-button
                        @click="addDomain"
                        v-if="keyword!='show'"
                        style="background:#409EFF;color:white"
                    >新增答题选项</el-button>
                  </div>
                  <el-form-item
                      style="display: flex"
                      v-for="(domain,index) in dynamicValidateForm.domains"
                      :label="domain.option"
                      :key="domain.option"
                      :prop="'domains.' + index + '.content'"
                      :rules="{required: true, message: '选项内容不能为空', trigger: 'blur'}"
                  >
                    <div style="display: flex">
                    <el-input v-model="domain.content" v-if="keyword!='show'" style="width: 20vw"></el-input>
                    <span v-if="keyword=='show'">{{domain.content}}</span>
                    <span
                        style="cursor: pointer"
                        class="linkDel"
                        v-if="keyword!='show'"
                        @click.prevent="removeDomain(domain,index)"
                    >删除</span>
                    </div>
                  </el-form-item>
                </div>


                <el-form-item
                    label="正确答案"
                    prop="answer_right"
                    :rules="{required: true, message: '正确答案不能为空', trigger: 'blur'}"
                >
                  <span v-if="keyword=='show'">{{dynamicValidateForm.answer_right.toString()}}</span>
                  <el-select
                      v-if="keyword!='show'"
                      v-model="dynamicValidateForm.answer"
                      style="width: 52vw;"
                      @change="getAnswer"
                      multiple
                      placeholder="请选择正确答案"
                  >
                    <el-option
                        v-for="item in dynamicValidateForm.domains "

                        :key="item.option"
                        :label="item.option"
                        :value="item.option"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item

                    label="答案提示"
                    :rules="[{ required: true, message: '请输入答案解析', trigger: 'blur' }]"
                >
                  <span v-if="keyword=='show'">1</span>
                  <el-input
                      v-if="keyword!='show'"
                      type="textarea"
                      v-model="hint"
                  ></el-input>
                </el-form-item>
                <el-form-item >
                  <el-button v-if="edit" type="primary" @click="editorObject">保存</el-button>
                  <el-button v-else type="primary" @click="createObject">创建</el-button>
                  <el-button @click="">重置</el-button>
                </el-form-item>
              </el-form>

            </div>
          </div>


      </div>
    </div>


  </main>




</template>

<script>
import File from "./file.vue";
import API from "../api/trainer/questionManager"
export default {
  components: {File},
  data(){
    return{
      foldSwitchStatus:false,
      selectedCategory:'',
      questionType:0,
      selectType:'',
      edit:false,
      typeList:[{
        name:'单选题'
      },
        {
          name:'多选题'
        },
        {
          name:'判断题'
        }],
      problemCategoryMap: new Map(),
      problemTagMap: new Map(),
      answerMap: new Map,
      level1: [],
      level2: [],
      problemCategories: [{
        parentCategory: '',
        categoryLevelTwo: []
      }],
      categoryId:[],
      tagId:'',
      tagList:[],
      alpha: [
        "A", "B", "C", "D", "E", "F", "G", "H",
      ],
      activeItem: [],
      title:'',
      hint:'',
      dynamicValidateForm: {
        type: "",
        domains: [
          {
            content: "",
            option: "A",
            answer:false,
            // key: Date.now()
          },

        ],
        content: "",
        answer_parse: "",
        answer: []
      },
      removeList: [],
      problemTags:[],
      company:0,
      companyList:[]

    }
  },
  mounted() {
      this.initObject()
      this.getProblemCategory()
      this.allCategory()
      this.allCompany()

    },
  methods:{
    initObject(){

      Loading.show();
      this.problem = LocalStorage.get(CURRENT_EDIT_PROBLEM);
      //如果传入problem参数则是编辑页面
      if(this.problem != undefined) {
        this.edit = true
        this.selectedCategory = this.problem.categoryName
        let substrings = this.problem.categoryId.split(',')
        let categoryname = this.problem.categorySlug.split(',')
        categoryname.forEach(e=>{
          this.activeItem.push(e)
        })

        this.categoryId = substrings.map(substring => parseInt(substring))
        switch (parseInt(this.problem.questionType)){
          case 2: this.selectType = '单选题'
            break;
          case 3: this.selectType = '多选题'
            break;
          case 4: this.selectType = '判断题'
            break;
        }
        this.company = this.problem.companyName
        this.tagId = this.problem.tagName
        this.title = this.problem.title
        this.removeDomain(this.dynamicValidateForm.domains[0],0)
        this.problem.itemList.forEach(e=>{
          this.initDomain(e)
        })
        this.dynamicValidateForm.domains.forEach(e=>{
          this.answerMap.set(e.content,e.option)
        })
        this.problem.itemList.forEach(e=>{
          if(e.answer){
            this.dynamicValidateForm.answer.push(this.answerMap.get(e.content))
          }
        })

        this.hint = this.problem.hint
      }
      else {
        this.problem = {};
      }
      Loading.hide();
    },
    //如果是编辑界面，则初始化选项
    initDomain(data){
      let temAlpha = [];
      if (this.dynamicValidateForm.domains.length > 8) {
        Message.info("抱歉，答题选项已经上限了");
        return;
      }
      let domainObj = []; //添加的答题选项的abc值保存
      let domainLen = this.dynamicValidateForm.domains.length; //答题选项长度获取
      let alphaObj = this.alpha.slice(0, domainLen); //截取alpha字符串长度作为数组
      this.dynamicValidateForm.domains.map(res => {

        domainObj.push(res.option);

      });
      let unqualList = this.getArrDifference(alphaObj, domainObj); //获取字符串中不相等的内容
      if (unqualList.length > 0) {
        let interList = this.array_intersection(unqualList, alphaObj); //交集的数组
        let alphaIndex = alphaObj.indexOf(interList[0]);
        this.dynamicValidateForm.domains.splice(alphaIndex, 0, {
          content: "",
          option: this.alpha[alphaIndex]
        });
      } else {
        this.dynamicValidateForm.domains.push({
          content: data.content,
          answer: data.answer,
          option: this.alpha[this.dynamicValidateForm.domains.length]
        });
      }
    },
    addDomain() {
      let temAlpha = [];
      if (this.dynamicValidateForm.domains.length > 8) {
        Message.info("抱歉，答题选项已经上限了");
        return;
      }
      let domainObj = []; //添加的答题选项的abc值保存
      let domainLen = this.dynamicValidateForm.domains.length; //答题选项长度获取
      let alphaObj = this.alpha.slice(0, domainLen); //截取alpha字符串长度作为数组
      this.dynamicValidateForm.domains.map(res => {

        domainObj.push(res.option);

      });
      let unqualList = this.getArrDifference(alphaObj, domainObj); //获取字符串中不相等的内容
      if (unqualList.length > 0) {
        let interList = this.array_intersection(unqualList, alphaObj); //交集的数组
        let alphaIndex = alphaObj.indexOf(interList[0]);
        this.dynamicValidateForm.domains.splice(alphaIndex, 0, {
          content: "",
          option: this.alpha[alphaIndex]
        });
      } else {
        this.dynamicValidateForm.domains.push({
          content: "",
          answer: false,
          option: this.alpha[this.dynamicValidateForm.domains.length]
        });
      }
    },
    array_intersection(a, b) {
      // 交集
      var result = [];
      for (var i = 0; i < b.length; i++) {
        var temp = b[i];
        for (var j = 0; j < a.length; j++) {
          if (temp === a[j]) {
            result.push(temp);
            break;
          }
        }
      }
      return result;
    },


    removeDomain(item, index) {
      this.removeList.push(index);
      var index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
      // if (this.dynamicValidateForm.answer_right.length > 0) {
      //   this.dynamicValidateForm.answer_right.forEach((res, index) => {
      //     if (res == item.option) {
      //       this.dynamicValidateForm.answer_right.splice(index, 1);
      //     }
      //   });
      // }
    },


    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function(v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    },

    allCategory() {

      let _this = this;
      let token = localStorage.getItem('token')
      API.getTags(token).then(res=>{
        this.tagList=res.data.content
        this.tagList.forEach(e=>{
          _this.problemTagMap.set(e.name, e.id);
        })

      }).catch(e=>{
        console.log(e)
      })



      API.questionCategoryList(token).then((res) => {
        console.log(res.data)
        if(res.data.success) {
          _this.categorys = res.data.content;
          // 将所有记录格式化成树形结构
          _this.level1 = [];
          console.log(539)
          console.log(_this.categorys)
          for (let i = 0; i < _this.categorys.length; i++) {
            let c = _this.categorys[i];
            _this.problemCategoryMap.set(c.problemCategorySlug.toString(), c.problemCategoryName);
            if (c.problemCategoryParentId === 0) {
              _this.level1.push(c);
            } else {
              _this.level2.push(c);
            }
          }
          console.log(_this.problemCategoryMap)
          _this.elTreeDataSource = []
          for (let i = 0; i < _this.level1.length; i++) {
            let elTreeParentData = {
              id: _this.level1[i].problemCategoryId,
              label: _this.level1[i].problemCategoryName,
              alias: _this.level1[i].problemCategorySlug,
              showPriority: _this.level1[i].showPriority,
              parentId: _this.level1[i].parentProblemCategoryId,
              children: [],
            }
            for (let j = 0; j < _this.level2.length; j++) {
              if (_this.level2[j].problemCategoryParentId === _this.level1[i].problemCategoryId) {
                let elTreeChildrenData = {
                  id: _this.level2[j].problemCategoryId,
                  label: _this.level2[j].problemCategoryName,
                  alias: _this.level2[j].problemCategorySlug,
                  showPriority: _this.level2[j].showPriority,
                  parentId: _this.level2[j].problemCategoryParentId,
                }
                elTreeParentData.children.push(elTreeChildrenData);
              }
            }
            _this.elTreeDataSource.push(elTreeParentData);
          }
          console.log(54)
          console.log(this.elTreeDataSource)
        }
      }).catch((err) => {
        console.log(err);
      });


    },

    getAnswer(){

      this.dynamicValidateForm.answer.forEach(r=>{
        this.dynamicValidateForm.domains.forEach(e=>{
            if(r === e.option){
              e.answer = true
            }else{
              e.answer = false
            }
        })

      })
      this.dynamicValidateForm.domains.forEach(e=>{
        this.dynamicValidateForm.answer.forEach(r=>{

          if(e.option === r){
            e.answer = true
          }
        })
      })
    },


    getProblemCategory() {
      let _this = this;
      let token = localStorage.getItem('token')
      API.questionCategoryList(token).then((res) => {
        if (res.data === 'Unauthorized' || res.data === 'Forbidden') {
          _this.$router.push({path: '/home'});
          return;
        }

        if (res.data) {
          _this.problemCategories = res.data.content;

        }

      }).catch((err) => {
        this.$notify.error("提交失败，请联系管理员");
        console.log(err);
      });
    },
    onCheck(name,problemCategoryId) {
      //点击子目录
      // if(parentName !== "") {
      //   if(!_this.activeItem.includes(parentName) && !_this.activeItem.includes(name)) {
      //     _this.activeItem.push(parentName);
      //   }
      // }
      if (this.activeItem.includes(name)) {
        console.log(this.activeItem)
        this.removeObj(this.activeItem, name);
        this.removeObj(this.categoryId,problemCategoryId);
      } else {
        this.activeItem.push(name)
        this.categoryId.push(problemCategoryId)
      }

      //显示选中的试题分类
      let categoryList = []
      for (let i = 0; i < this.activeItem.length; i++) {
        let currentKey = this.activeItem[i].toString();
        let currentCategoryName = this.problemCategoryMap.get(currentKey);
        categoryList.push(currentCategoryName);
      }

      this.selectedCategory = categoryList.join(",");
    },
    removeObj(array, obj) {
      let index = -1;
      for (let i = 0; i < array.length; i++) {
        if (array[i] === obj) {
          array.splice(i, 1);
          index = i;
          break;
        }
      }
      return index;
    },
    editorObject(){

      let token = localStorage.getItem('token')
      let companyId = 0
      console.log(3654)
      console.log(this.tagId)
      console.log($('#problem-type').val())
      if($('#problem-type').val()==='单选题'){
        console.log(2)
        this.questionType = 2
      }else if($('#problem-type').val()==='多选题'){
        console.log(3)
        this.questionType = 3
      }else if($('#problem-type').val()==='判断题'){
        console.log(4)
        this.questionType = 4
      }
      console.log(this.questionType)

      this.companyList.forEach(e=>{
        if(e.name===$('#problem-company').val()){
          companyId =e.id
        }
      })
      let param = {}
      if(companyId!==0){
        param.companyId =companyId
      }
      param.id = this.problem.id

      if(this.questionType!==0){
        param.questionType = this.questionType
      }
      let tagId = []
      tagId.push(this.problemTagMap.get(this.tagId))
      param.categoryId =JSON.stringify(this.categoryId)
      param.tagId =JSON.stringify(tagId)
      param.item = this.dynamicValidateForm.domains
      param.hint = this.hint
      // param.answer = this.dynamicValidateForm.answer
      param.title = this.title
      console.log(param)

      API.createObject(param,token).then(res=>{
        this.$message({
          message:'编辑成功！',
          type:"success"
        })
      }).then(res=>{
        // setTimeout(function (){window.location.reload(true)},1000)
      }).catch(e=>{
        console.log(e)
      })
    },


    createObject(){

      let token = localStorage.getItem('token')
      let companyId = 0
      console.log(3654)
      console.log(this.tagId)
      console.log($('#problem-type').val())
      if($('#problem-type').val()==='单选题'){
        console.log(2)
        this.questionType = 2
      }else if($('#problem-type').val()==='多选题'){
        console.log(3)
        this.questionType = 3
      }else if($('#problem-type').val()==='判断题'){
        console.log(4)
        this.questionType = 4
      }
      console.log(this.questionType)

      this.companyList.forEach(e=>{
        if(e.name===$('#problem-company').val()){
          companyId =e.id
        }
      })
      let param = {}
      if(companyId!==0){
        param.companyId =companyId
      }

      if(this.questionType!==0){
        param.questionType = this.questionType
      }
      let tagId = []
      tagId.push(this.problemTagMap.get(this.tagId))
      param.categoryId =JSON.stringify(this.categoryId)
      param.tagId =JSON.stringify(tagId)
      param.item = this.dynamicValidateForm.domains
      param.hint = this.hint
      // param.answer = this.dynamicValidateForm.answer
      param.title = this.title
      console.log(param)
      API.createObject(param,token).then(res=>{
        this.$message({
          message:'创建成功！',
          type:"success"
        })
      }).then(res=>{
        // setTimeout(function (){window.location.reload(true)},1000)
      }).catch(e=>{
        console.log(e)
      })
    },
    /**
     * 所有公司查询
     */

    allCompany(){
      let token = localStorage.getItem('token')
      API.getCompany(token).then(res=>{
        this.companyList = res.data.content
        console.log(this.companyList)
      }).catch(e=>{
        console.log(e)
      })
    },
  },
}
</script>

<style  scoped>

.active {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background: #efc531;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.Classification {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background:#e9ecef;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.addquestion {
  .domain_title {
    margin: 10px;
    justify-content: space-between;
    display: flex;
    span {
      color: #606266;
      font-size: 14px;
      align-items: center;
      display: flex;
    }
    el-button {
      background: #3a8ee6;
    }
  }
  .linkDel {
    color: #3a8ee6;
    width: 70px;
    text-align: center;
  }
  ::v-deep  .el-form-item__content {
    display: flex;
  }
  form {
    width: 52vw;

  }
  .question-title {
    font-size: 22px;
    color: #88909c;
    padding: 20px;
    display: flex;
    justify-content: space-between;
  }
}

</style>